import jQuery from 'jquery';

const WebSocketWrapper = (function ($) {
    let socket, settings, W = function (opt) {
        settings = $.extend ({}, opt || {});
    };
    W.prototype = {
        connect : function (url) {
            let self = this;
            socket = new WebSocket (url);
            if ('onopen' in settings) {
                socket.onopen = function () {
                    settings ['onopen'].call (self, settings);
                };
            }
            if ('onmessage' in settings) {
                socket.onmessage = function (e) {
                    settings ['onmessage'].call (self, e.data, settings);
                }
            }

            socket.onclose = function () {
                if (settings ['debug']) {
                    console.log ('socket closed');
                }
                if ('onclose' in settings) {
                    settings ['onclose'].call (self, settings);
                }
            };
            if ('onerror' in settings) {
                socket.onerror = function (e) {
                    settings ['onclose'].call (self, e, settings);
                }
            }

            return self;
        },
        send : function (message) {
            if (socket) {
                socket.send (message);
            }
        },
        disconnect : function () {
            if (socket) {
                socket.close ();
            }
        }
    };
    return W;
})(jQuery);

export default WebSocketWrapper;